package com.workflow.server.service.impl;

import com.workflow.server.bean.dto.ChildNode;
import com.workflow.server.bean.dto.Properties;
import com.workflow.server.service.IFlowNodeCreateHandler;
import com.workflow.server.service.IFlowNodeCreateHandlerContext;
import org.camunda.bpm.model.bpmn.builder.AbstractFlowNodeBuilder;
import org.camunda.bpm.model.bpmn.builder.StartEventBuilder;
import org.camunda.bpm.model.bpmn.builder.UserTaskBuilder;
import org.camunda.bpm.model.bpmn.instance.FlowNode;
import org.camunda.bpm.model.bpmn.instance.Process;
import org.camunda.bpm.model.bpmn.instance.StartEvent;
import org.camunda.bpm.model.xml.ModelInstance;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.glassfish.jersey.internal.jsr166.Flow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

import static com.workflow.server.enums.FlowNodeType.*;

/**
 * <p>title:发起人节点处理器</p>
 *
 * @author ForeverKobe
 */
@Component
public class ApprovalNodeCreateHandler implements IFlowNodeCreateHandler {
    @Autowired
    IFlowNodeCreateHandlerContext flowNodeCreateHandlerContext;

    @Override
    public FlowNode doCreateNode(String parentNodeId, ChildNode childNode, Process process, Map<String, ChildNode> childNodeMap) {
        childNodeMap.put(childNode.getId(), childNode);
        ModelInstance modelInstance = process.getModelInstance();
        // 获取父节点,发起人节点的父节点是开始节点
        FlowNode parentNode = modelInstance.getModelElementById(parentNodeId);
        String id = "UserTask-" + childNode.getId();
        String name = childNode.getName();
        String sequenceId = parentNodeId + "-" + id;
        AbstractFlowNodeBuilder flowNodeBuilder = parentNode.builder();
        UserTaskBuilder userTaskBuilder = flowNodeBuilder.sequenceFlowId(sequenceId)
                .userTask(id)
                .name(name);

        Properties props = childNode.getProps();
        String assignedType = Optional.ofNullable(props.getAssignedType()).orElse("SELF");
        if ("SELF".equals(assignedType)) {
            userTaskBuilder.camundaAssignee("${initiator}");
        }
        ChildNode children = childNode.getChildren();


        userTaskBuilder.done();
        //后面无节点时，直接返回
        if (children == null || EMPTY.getType().equals(children.getType()) || children.getId() == null) {
            return userTaskBuilder.getElement();
        }
        //继续递归后面的节点
        return flowNodeCreateHandlerContext.createNode(id, children, process, childNodeMap);
    }

    @Override
    public String getType() {
        return APPROVAL.getType();
    }
}
